<template>
  <div class="box-border w-full h-full task-setting">
    <div class="flex items-center gap-2 text-lg">
      <span class="text-[#030014]/60">装配检测</span>
      <span class="text-[#030014]/60">></span>
      <span class="text-[#030014]"> 任务设置</span>
    </div>
    <div
      class="box-border pb-10 p-7 bg-white/50 rounded-[12px] border_white mt-7 h-[calc(100%-340px)] w-[95%] mx-auto overflow-y-auto scrollbar scrollbar-thumb-gray-300"
    >
      <!-- 基础信息部分 -->
      <div class="flex basic-info">
        <div class="text-[20px] font-bold">基础信息</div>
        <el-form ref="basicFormRef" :model="basicFormData" :rules="basicRules" label-width="120px">
          <el-form-item label="任务名称" prop="taskName">
            <el-input v-model="basicFormData.taskName" readonly class="!w-[400px]" />
          </el-form-item>
          <el-form-item label="执行人" prop="executor">
            <el-input v-model="basicFormData.executor" placeholder="请输入" class="!w-[400px]" />
          </el-form-item>
          <el-form-item label="模型" prop="model">
            <el-select v-model="basicFormData.model" placeholder="请选择模型" class="!w-[400px]">
              <el-option
                v-for="item in modelList"
                :key="item.id"
                :label="item.model_cname"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div class="text-[#606266] text-sm ml-[150px]">
        <span class="text-[#f56c6c]">* </span>检测目标与准确性设置
      </div>
      <div v-if="basicFormData.model" class="pl-36 targets-grid">
        <div v-for="(target, index) in target" :key="index" class="target-item">
          <div class="flex items-center gap-4">
            <div class="image-placeholder">
              <el-image
                :src="target.pic_url"
                fit="cover"
                class="image-placeholder__img"
                :preview-src-list="[target.pic_url]"
                :initial-index="0"
                preview-teleported
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon size="20"><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
            </div>
            <div class="target-name">{{ target.detect_target_cname }}</div>
          </div>

          <div class="flex items-center gap-4 slider-container">
            <el-slider
              v-model="target.accuracy"
              show-input
              size="small"
              :min="0"
              :max="10"
              :marks="{ 0: '0', 10: '10' }"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 视频设置 -->
    <div
      class="p-7 video-settings bg-white/50 rounded-[12px] border_white mt-7 h-[164px] w-[95%] mx-auto box-border flex overflow-y-auto scrollbar scrollbar-thumb-gray-300"
    >
      <div class="text-[20px] font-bold mb-4">视频设置</div>
      <el-form ref="videoFormRef" :model="videoFormData" :rules="videoRules" label-width="120px">
        <el-form-item label="任务名称" prop="videoTask">
          <el-select v-model="videoFormData.videoTask" placeholder="请选择" class="!w-[400px]">
            <el-option label="摄像头" :value="0" />
            <el-option label="本地视频" :value="1" />
          </el-select>
        </el-form-item>

        <template v-if="videoFormData.videoTask === 0">
          <el-form-item label="选择摄像头" prop="camera">
            <el-select v-model="videoFormData.camera" placeholder="请选择摄像头" class="!w-[400px]">
              <el-option
                v-for="item in cameraList"
                :key="item.camera_id"
                :label="item.cname"
                :value="item.camera_url"
              />
            </el-select>
          </el-form-item>
        </template>

        <template v-if="videoFormData.videoTask === 1">
          <el-form-item label="上传视频" prop="videoFile">
            <el-upload
              class="!w-[400px]"
              action="#"
              :auto-upload="false"
              accept=".mp4,.avi,.mov"
              :on-change="handleVideoUpload"
              :limit="1"
              :on-exceed="handleExceed"
            >
              <el-button type="primary">选择视频文件</el-button>
            </el-upload>
          </el-form-item>
        </template>
      </el-form>
    </div>

    <!-- 底部按钮 -->
    <div class="action-buttons">
      <el-button type="primary" plain class="!w-[200px] !h-[40px]" @click="handleCancel"
        >退出</el-button
      >
      <el-button type="success" plain class="!w-[200px] !h-[40px]" @click="handleStart"
        >开始</el-button
      >
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { Picture } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { useDateFormat, useNow } from '@vueuse/core'
import Box from '../assets/images/box.png'
import { getModelDetail, getModelList } from '@/api/model'
import { getCameraList, createTask } from '@/api/task'
const router = useRouter()
const now = useNow()
const taskName = computed(() => {
  return `${useDateFormat(now, 'YYYYMMDDHHmm').value}的任务`
})

const basicFormData = ref({
  taskName: taskName.value,
  executor: 'Az',
  model: '',
})

const videoFormData = ref({
  videoTask: '',
  camera: '',
  videoFile: null,
})

const currentModelId = ref('')
watch(
  () => basicFormData.value.model,
  async (newVal) => {
    console.log('🐯 ~ watch ~ newVal:', newVal)
    // 请求该模型的检测目标
    const res = await getModelDetail({ id: newVal })
    console.log('🐯 ~ res:', res)
    // 处理图片URL
    if (res.data.targets) {
      res.data.targets = res.data.targets.map((item) => ({
        ...item,
        pic_url: item.pic_url ? `${import.meta.env.VITE_IMG_URL}${item.pic_url}` : '',
      }))
    }
    currentModelId.value = newVal
    target.value = res.data.targets
  },
)
// 检测目标数据
const target = ref([])

const basicFormRef = ref(null)
const videoFormRef = ref(null)

// 基础信息表单验证规则
const basicRules = {
  taskName: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
  model: [{ required: true, message: '请选择模型', trigger: 'change' }],
}

// 视频设置表单验证规则
const videoRules = {
  videoTask: [{ required: true, message: '请选择视频任务类型', trigger: 'change' }],
  camera: [{ required: true, message: '请选择摄像头', trigger: 'change' }],
  videoFile: [{ required: true, message: '请上传视频文件', trigger: 'change' }],
}

const handleCancel = () => {
  // 处理退出逻辑
  router.go(-1)
}

const handleStart = async () => {
  // 同时验证两个表单
  const [basicValid, videoValid] = await Promise.all([
    basicFormRef.value?.validate().catch(() => false),
    videoFormRef.value?.validate().catch(() => false),
  ])

  if (basicValid && videoValid) {
    // 更新目标准确度
    const res = await createTask({
      task_name: basicFormData.value.taskName,
      executor: basicFormData.value.executor,
      video_type: videoFormData.value.videoTask,
      video_url: videoFormData.value.camera,
      model: {
        model_id: currentModelId.value,
        target: target.value.map((item) => ({
          ...item,
          pic_url: item.pic_url.replace(import.meta.env.VITE_IMG_URL, ''),
        })),
      },
    })
    const pid = res.data.pid
    const taskId = res.data.task_id
    router.push({
      path: '/task_starting',
      query: {
        taskName: basicFormData.value.taskName,
        pid,
        taskId,
        rtspUrl: res.data.rtsp_ouput_url,
      },
    })
  } else {
    console.log('表单验证失败')
  }
}

// 新增视频上传处理函数
const handleVideoUpload = (file) => {
  // 检查文件大小（500MB = 500 * 1024 * 1024 bytes）
  const maxSize = 500 * 1024 * 1024
  if (file.raw.size > maxSize) {
    ElMessage.error('视频文件大小不能超过500MB')
    return false
  }
  videoFormData.value.videoFile = file.raw
}

// 添加超出文件数量限制的处理函数
const handleExceed = () => {
  ElMessage.error('只能上传一个视频文件')
}

const modelList = ref([])
const getModelLists = async () => {
  const res = await getModelList()
  console.log('🐯 ~ getModelList ~ res:', res)
  modelList.value = res.data
}
getModelLists()

const cameraList = ref([])
const getCameraLists = async () => {
  const res = await getCameraList()
  cameraList.value = res.data
}
getCameraLists()
// 获取模型列表
</script>

<style scoped>
.task-setting {
  padding: 20px 60px;

  .targets-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 50px;
    margin-top: 28px;
  }

  .target-item {
    .image-placeholder {
      width: 88px;
      height: 56px;
      background: #f5f7fa;
      border-radius: 4px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 20px;

      :deep(.el-image) {
        width: 100%;
        height: 100%;
      }
    }

    .target-name {
      font-size: 14px;
      margin: 8px 0;
      text-align: center;
    }

    .slider-container {
      padding: 0 10px;
    }

    .accuracy-control {
      display: flex;
      justify-content: center;
      margin-top: 10px;
    }
  }

  .action-buttons {
    display: flex;
    justify-content: center;
    gap: 200px;
    margin-top: 40px;
  }

  .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    color: #909399;
  }
}

:deep(.el-input-number--small) {
  width: 80px !important;
}

:deep(.el-form-item__label) {
  font-size: 14px;
}

:deep(.el-slider__button) {
  width: 12px !important;
  height: 12px !important;
}
</style>
